package com.pe.salem.main;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import model.Banco;
import model.Categoria;
import model.Establecimiento;
import model.Transaccion;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import procesador.ProcesadorSMS;
import android.R;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Launcher extends Activity {

	/** Colors to be used for the pie slices. */
	private static int[] COLORS = new int[] { Color.RED, Color.GREEN,
			Color.BLUE, Color.MAGENTA, Color.CYAN, Color.YELLOW };
	/** The main series that will include all the data. */
	private CategorySeries mSeries = new CategorySeries("");
	/** The main renderer for the main dataset. */
	private DefaultRenderer mRenderer = new DefaultRenderer();

	private GraphicalView mChartView;
	private LinearLayout lygrafico;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		lygrafico = new LinearLayout(this);
		TextView tvLista = new TextView(this);
		

		Uri uriSMSURI = Uri.parse("content://sms/inbox");
		Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,
				null);
		String sms = "";
		int dateColumn = cur.getColumnIndex("date");
		int numberColumn = cur.getColumnIndex("address");
		int bodyColumn = cur.getColumnIndex("body");
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
		ProcesadorSMS procesador = new ProcesadorSMS();
		Transaccion transaccion = null;
		List<Transaccion> listaTransaccion = new ArrayList<Transaccion>();
		DisplayMetrics metrics = this.getResources().getDisplayMetrics();
		float val = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 18, metrics);
		while (cur.moveToNext()) {
			if (cur.getString(numberColumn).equals("7270")) {
				if (procesador.validarSMSScotiaBank(cur.getString(bodyColumn))) {
					transaccion = new Transaccion();
					transaccion.setBanco(new Banco("SCOTIABANK"));
					transaccion.setCategoria(new Categoria(""));
					transaccion.setCuenta("");
					transaccion.setFecha(new Date(Long.parseLong(cur
							.getString(dateColumn))));
					transaccion.setMonto(procesador.extraerImporte(cur
							.getString(bodyColumn)));
					transaccion.setDetalle(procesador.procesarScotiaBank(cur
							.getString(bodyColumn)));
					listaTransaccion.add(transaccion);
					sms += "SCOTIABANK : Importe S/. " + transaccion.getMonto()
							+ " fecha="
							+ sdf.format(transaccion.getFecha()).toString()
							+ " detalle gasto=" + transaccion.getDetalle()
							+ "\n";

					mSeries.add(transaccion.getMonto() + ""  + transaccion.getEstablecimiento().getNombre(),
							transaccion.getMonto());
					SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
					renderer.setColor(COLORS[(mSeries.getItemCount() - 1)
							% COLORS.length]);
					renderer.setChartValuesTextSize(val);
					mRenderer.addSeriesRenderer(renderer);
					mRenderer.setChartTitleTextSize(val);
					mRenderer.setLabelsTextSize(val);
				}

			}

			if (cur.getString(numberColumn).equals("595")) {
				if (procesador.validarSMSBBVA(cur.getString(bodyColumn))) {
					transaccion = new Transaccion();
					transaccion.setBanco(new Banco("BBVA Continental"));
					transaccion.setCategoria(new Categoria(""));
					transaccion.setCuenta("");
					transaccion.setFecha(new Date(Long.parseLong(cur
							.getString(dateColumn))));
					transaccion.setMonto(procesador.extraerImporte(cur
							.getString(bodyColumn)));
					transaccion.setDetalle(procesador.procesarBBVA(cur
							.getString(bodyColumn)));
					transaccion.setEstablecimiento(new Establecimiento(
							procesador.obtenerNombreEstablecimiento(cur
							.getString(bodyColumn))));
					listaTransaccion.add(transaccion);
					sms += "BBVA : Importe S/. " + transaccion.getMonto()
							+ " fecha="
							+ sdf.format(transaccion.getFecha()).toString()
							+ " detalle gasto=" + transaccion.getDetalle()
							+ " establecimiento=" + transaccion.getEstablecimiento().getNombre()
							+ "\n";

					mSeries.add(transaccion.getMonto() + " " + transaccion.getEstablecimiento().getNombre(),
							transaccion.getMonto());
					SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
					renderer.setColor(COLORS[(mSeries.getItemCount() - 1)
							% COLORS.length]);
					renderer.setChartValuesTextSize(val);
					mRenderer.addSeriesRenderer(renderer);
					mRenderer.setChartTitleTextSize(30);
					mRenderer.setLabelsTextSize(30);
					mRenderer.setLegendTextSize(30);

//					mRenderer.setChartTitleTextSize(this.getResources().getDimension(R.dimen.graph_chart_text_size));
//					mRenderer.setAxisTitleTextSize(this.getResources().getDimension(R.dimen.graph_axis_title_text_size));
//					mRenderer.setLabelsTextSize(this.getResources().getDimension(R.dimen.graph_labels_text_size));
//					mRenderer.setLegendTextSize(this.getResources().getDimension(R.dimen.graph_legend_text_size));
//					mRenderer.setLegendHeight(this.getResources().getDimensionPixelOffset(R.dimen.graph_legend_height));
//					mRenderer.setMargins(new int[]{
//					        this.getResources().getDimensionPixelOffset(R.dimen.graph_margin_top),
//					        this.getResources().getDimensionPixelOffset(R.dimen.graph_margin_left_mood),
//					        this.getResources().getDimensionPixelOffset(R.dimen.graph_margin_bottom),
//					        this.getResources().getDimensionPixelOffset(R.dimen.graph_margin_right)});
//					    }
				}

			}
		}
		tvLista.setText(sms);
		LinearLayout layout = new LinearLayout(this);
		mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
		layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		mChartView.repaint();
		lygrafico.addView(layout);
		lygrafico.addView(tvLista);
		// tvLista.setMovementMethod(new ScrollingMovementMethod());
		//BudgetDoughnutChart chart = new BudgetDoughnutChart();
		
		//startActivity(chart.execute(this));
		setContentView(lygrafico);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mChartView == null) {
			LinearLayout layout = new LinearLayout(this);
			;
			mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
			mRenderer.setClickEnabled(true);
			mChartView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					SeriesSelection seriesSelection = mChartView
							.getCurrentSeriesAndPoint();
					if (seriesSelection == null) {
						Toast.makeText(Launcher.this,
								"No chart element selected", Toast.LENGTH_SHORT)
								.show();
					} else {
						for (int i = 0; i < mSeries.getItemCount(); i++) {
							mRenderer.getSeriesRendererAt(i).setHighlighted(
									i == seriesSelection.getPointIndex());
						}
						mChartView.repaint();
						Toast.makeText(
								Launcher.this,
								"Chart data point index "
										+ seriesSelection.getPointIndex()
										+ " selected" + " point value="
										+ seriesSelection.getValue(),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
			layout.addView(mChartView, new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		} else {
			mChartView.repaint();
		}
	}
	
	
}
